import { DirectiveBinding, VNode } from "vue";

// 触发自定义输入事件
const triggerInputEvent = (target: HTMLInputElement): void => {
  const event = new Event("input", { bubbles: true });
  target.dispatchEvent(event);
};

// 显示提示信息
const showHint = (hintEl: HTMLElement, message: string): void => {
  hintEl.textContent = message;
  hintEl.style.display = "block";
  setTimeout(() => {
    hintEl.style.display = "none";
  }, 2000);
};

const NoSpaceDirective = {
  mounted(el: HTMLElement, binding: DirectiveBinding, vnode: VNode) {
    // 只处理 el-input 组件
    if (!el.classList.contains("el-input") && !el.classList.contains("el-textarea")) return;

    // 获取实际输入元素（input 或 textarea）
    let input: HTMLInputElement | HTMLTextAreaElement | null = el.querySelector("input");
    console.log(input, "input");
    if (!input) return;
    console.log(input.type, "input");
    console.log(input, "input");

    // 排除不需要处理的类型
    const excludeTypes = ["password", "checkbox", "radio", "file", "hidden"];
    if (input instanceof HTMLInputElement && excludeTypes.includes(input.type)) return;

    // 创建提示元素 - 使用 Element UI 的样式
    const hint = document.createElement("div");
    hint.className = "el-form-item__error";
    hint.style.display = "none";
    hint.style.top = "-14px";
    hint.style.height = "14px";
    const hintMessage = "请不要输入首尾空格";

    // 插入提示元素
    el.parentNode?.insertBefore(hint, el.nextSibling);

    // 处理输入事件
    const handleInput = (e: Event): void => {
      const target = e.target as HTMLInputElement;

      // 禁止在开头输入空格
      if (target.selectionStart === 0 && (e as InputEvent).data === " ") {
        showHint(hint, hintMessage);
        target.value = target.value.trim();
        triggerInputEvent(target);
        return;
      }

      // 实时去除末尾空格
      const originalValue = target.value;
      const trimmedValue = originalValue.trim();
      if (originalValue !== trimmedValue) {
        showHint(hint, hintMessage);
        target.value = trimmedValue;
        triggerInputEvent(target);
      }
    };

    // 处理失去焦点事件
    const handleBlur = (e: Event): void => {
      const target = e.target as HTMLInputElement;
      const originalValue = target.value;
      const trimmedValue = originalValue.trim();

      if (originalValue !== trimmedValue) {
        showHint(hint, hintMessage);
        target.value = trimmedValue;
        triggerInputEvent(target);
      }
    };

    // 处理粘贴事件
    // const handlePaste = (e: ClipboardEvent): void => {
    //   const clipboardData = e.clipboardData;
    //   const pastedText = clipboardData?.getData("text") || "";

    //   if (pastedText.startsWith(" ") || pastedText.endsWith(" ")) {
    //     showHint(hint, hintMessage);
    //   }
    // };

    // 添加事件监听
    input.addEventListener("input", handleInput);
    input.addEventListener("blur", handleBlur);
    // input.addEventListener("paste", handlePaste);

    // 保存事件处理函数以便卸载时移除
    el._noSpaceHandlers = {
      input: handleInput,
      blur: handleBlur,
      // paste: handlePaste,
    };
  },

  unmounted(el: HTMLElement) {
    // 移除事件监听
    const input = el.querySelector("input") as HTMLInputElement;
    if (input && el._noSpaceHandlers) {
      input.removeEventListener("input", el._noSpaceHandlers.input);
      input.removeEventListener("blur", el._noSpaceHandlers.blur);
      // input.removeEventListener("paste", el._noSpaceHandlers.paste);
    }
  },
};

// 扩展 HTMLElement 类型声明
declare global {
  interface HTMLElement {
    _noSpaceHandlers?: {
      input: (e: Event) => void;
      blur: (e: Event) => void;
      // paste: (e: ClipboardEvent) => void;
    };
  }
}

export default NoSpaceDirective;
